package com.fixme4trade.persistence;

import java.util.List;
import java.util.StringTokenizer;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.slf4j.Logger;
import br.gov.frameworkdemoiselle.stereotype.PersistenceController;
import br.gov.frameworkdemoiselle.template.JPACrud;
import com.fixme4trade.domain.Product;
import com.fixme4trade.domain.Seller;

@PersistenceController
public class ProductDAO extends JPACrud<Product, Long> {
	
	private static final long serialVersionUID = 1L;

	@Inject
	@SuppressWarnings("unused")
	private Logger logger;
	
	@Inject
	private EntityManager em;
	
	@Inject
	private Product product;

	@SuppressWarnings("unchecked")
	public List<Product> getProductsByQuery(String query) {
//		StringTokenizer st = new StringTokenizer(query);
//		
//		while (st.hasMoreTokens()) {
//			token = st.nextToken();
//		}		
		
		Query queryObj;
		
		if (query == null) {
			queryObj = getEntityManager().createNativeQuery("SELECT * FROM Product p", Product.class);
		} else {
			//String queryPlusPercent = "%"+ query +"%";
			queryObj = getEntityManager().createNativeQuery("SELECT * FROM Product p WHERE p.description LIKE '%"+query+"%'", Product.class);
		}		

		return queryObj.getResultList();		
	}	
	
	@SuppressWarnings("unchecked")
	public List<Product> getProductsBySeller(Seller seller) {

		Query queryObj = getEntityManager().createQuery("SELECT p FROM Product p WHERE p.owner.id = "+seller.getId(), Product.class);		

		return queryObj.getResultList();
	}	
}
